package com.yb.web.goods;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import com.opensymphony.xwork2.ActionContext;
import com.yb.base.web.BaseAction;
import com.yb.bussiness.global.SystemLogService;
import com.yb.bussiness.global.SystemLogServiceImpl;
import com.yb.bussiness.goods.CategoryService;
import com.yb.bussiness.goods.CategoryServiceImpl;
import com.yb.bussiness.goods.GoodsService;
import com.yb.bussiness.goods.GoodsServiceImpl;
import com.yb.bussiness.shoper.BrandService;
import com.yb.bussiness.shoper.BrandServiceImpl;
import com.yb.bussiness.tribune.TribuneService;
import com.yb.bussiness.tribune.TribuneServiceImpl;
import com.yb.bussiness.type.TypeService;
import com.yb.bussiness.type.TypeServiceImpl;
import com.yb.domain.goods.TgBrand;
import com.yb.domain.goods.TgCategory;
import com.yb.domain.goods.TgGoods;
import com.yb.domain.goods.TgType;
import com.yb.domain.member.TsSysuser;
import com.yb.domain.tribune.Tribune;
import com.yb.util.comm.Contants;
import com.yb.util.comm.RequestUtil;
import com.yb.util.comm.StringUtil;
import com.yb.util.file.FileUtil;
import com.yb.util.file.XmlUtil;
import com.yb.util.framework.PageUtil;

public class GoodsAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private TgGoods goods;
	private TgBrand brand;
	private TgType tgType;

	private GoodsService service;
	private File imgcomp;
	private File imgcomp1;
	private CategoryService categoryService;
	private TribuneService tribuneService;
	private String imgcompFileName;
	private String imgcomp1FileName;
	private int total;
	private List rows;
	private List<TgBrand> brandList;
	private List<TgType> typeList;
	private String typeId;
	private String brandId;
	private TypeService typeService;
	private String categoryId;
	private int pageNo;
	private int limit;
	private BrandService bService;
	private int page;
	private List<TgCategory> catrows;
	private CategoryService catsrvice;
	private SystemLogService systemLogService;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public GoodsAction() {
		service = new GoodsServiceImpl();
		categoryService = new CategoryServiceImpl();
		typeService = new TypeServiceImpl();
		bService = new BrandServiceImpl();
		tribuneService = new TribuneServiceImpl();
		catsrvice = new CategoryServiceImpl();
		systemLogService = new SystemLogServiceImpl();
	}

	public String addGoodsPage() {
		goods = new TgGoods();
		goods.setId(Long.valueOf(0));
		try {
			rows = categoryService.findAll(1, 50);
		} catch (Exception e) {
			log.error("显示品牌产品分类错误", e);
		}
		return "addGoodsPage";
	}

	public String addGoods() {
		TgBrand brand = (TgBrand) RequestUtil.getLoginUserFromSession(request,
				"brandInfo");
		TsSysuser user = (TsSysuser) RequestUtil.getLoginUserFromSession(
				request, Contants.SESSION_USER);
		try {
			String basePath = request.getSession().getServletContext()
					.getRealPath("/");
			String compressPath = XmlUtil.getValue("imgPath", "sysConfig")
					+ "/";
			String fileName = "";
			if (imgcomp != null) {
				fileName = new Date().getTime()
						+ imgcompFileName.substring(imgcompFileName
								.lastIndexOf("."));
				if (FileUtil.doUpFile(basePath + compressPath + fileName,
						imgcomp)) {
					goods.setImgSrc(compressPath + fileName);
				}
			}
			if (imgcomp1 != null) {
				fileName = new Date().getTime()
						+ imgcomp1FileName.substring(imgcomp1FileName
								.lastIndexOf("."));
				if (FileUtil.doUpFile(basePath + compressPath + fileName,
						imgcomp1)) {
					goods.setBigImg(compressPath + fileName);
				}
			}
			if (0 != goods.getId())
				goods
						.setCreatetime(service.read(goods.getId())
								.getCreatetime());
			if (null != brand && "2".equals(user.getType())) {
				goods.setCategoryId(brand.getCid());
				goods.setBrandId(brand.getId());
			} else {
				goods.setCategoryId(Long.valueOf((null == categoryId || ""
						.equals(categoryId)) ? "0" : categoryId));
				goods.setBrandId(Long.valueOf((null == brandId || ""
						.equals(brandId)) ? "0" : brandId));
			}
			goods.setTypeId(Long
					.valueOf((null == typeId || "".equals(typeId)) ? "0"
							: typeId));
			 if(goods.getId() == null)
				 systemLogService.saveSystemLog(request, "抢购产品设置", "新增--"+goods.getName());
			 else
				 systemLogService.saveSystemLog(request, "抢购产品设置", "修改--"+goods.getName());
			service.saveOrUpdate(goods);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (null != brand && "2".equals(user.getType())) {
			return "brandSuccess";
		}
		return "success";
	}

	@SuppressWarnings("unchecked")
	public String search() {
		menuCls = RequestUtil.getParam(request, "menuCls", "");
		Map<String, String> map = new HashMap<String, String>();
		int page = RequestUtil.getParam(request, "page", 1);
		int row = RequestUtil.getParam(request, "rows", 10);
		String name = RequestUtil.getParam(request, "name", "");
		String typeId = RequestUtil.getParam(request, "typeId", "");
		String brandId = RequestUtil.getParam(request, "brandId", "");
		String categoryId1 = RequestUtil.getParam(request, "categoryId1", "");
		String categoryId2 = RequestUtil.getParam(request, "categoryId2", "");
		String autding = RequestUtil.getParam(request, "autding", "");
		map.put("name", name);
		map.put("typeId", typeId);
		map.put("brandId", brandId);
		map.put("categoryId1", categoryId1);
		map.put("categoryId2", categoryId2);
		map.put("autding", autding);
		PageUtil pu = service.getList(map, page, row);
		total = pu.getTotalRecords();
		rows = pu.getList();
		return Contants.JSONSTRING_RESULT_NAME;
	}

	public String moreGoods() {
		if (pageNo == 0)
			pageNo = 1;
		if (limit == 0)
			limit = 20;
		ActionContext context = ActionContext.getContext();
		PageUtil goodslist = service.findGoodsByCategoryId(new Long(brandId),
				pageNo, limit, false);
		context.put("goodslist", goodslist);
		Map<String, String> parameMap = new HashMap<String, String>();
		List<TgBrand> brandlist = bService.findAllShoper(parameMap);
		ActionContext.getContext().put("brandlist", brandlist);
		TgCategory tc = categoryService.findById(Long.valueOf(brandId));
		ActionContext.getContext().put("categoryname", tc.getName());
		return "toMoreGoods";
	}

	/**
	 * 后台检索帖子
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String searchTribune() {
		TsSysuser  tsSysuser = (TsSysuser) RequestUtil.getLoginUserFromSession(request, Contants.SESSION_USER);
		menuCls = RequestUtil.getParam(request, "menuCls", "");
		Map<String, String> map = new HashMap<String, String>();
		int page = RequestUtil.getParam(request, "page", 1);
		int row = RequestUtil.getParam(request, "rows", 10);
		String startTime = RequestUtil.getParam(request, "startTime", "");
		String endTime = RequestUtil.getParam(request, "endTime", "");
		String flag = RequestUtil.getParam(request, "flag", "");
		String title = RequestUtil.getParam(request, "title", "");
		String userid = RequestUtil.getParam(request, "userid", "");
		if("".equals(userid)&&!"manageT".equals(flag))
			userid = tsSysuser.getId().toString();
		map.put("title", StringUtil.getStringNoSpace(title));
		map.put("userid", userid);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		int count = tribuneService.getCount(map);
		List<Tribune> list = tribuneService.getList(map, page, row);
		if (list != null && list.size() > 0) {
			total = count;
			rows = list;
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	public String deleteGoods() {
		String id = RequestUtil.getParam(request, "id", "");
		String idString = RequestUtil.getParam(request, "idString", "");

		boolean isFlag = false;
		if (!"".equals(id)){
			systemLogService.saveSystemLog(request, "抢购产品设置", "删除抢购产品--"+service.getById(id).getName());
			isFlag = service.deleteById(id);
		}else{
			String[] delteid = idString.split("_");
			try {
				for (int i = 0; i < delteid.length; i++) {
					systemLogService.saveSystemLog(request, "抢购产品设置", "删除抢购产品--"+service.getById(delteid[i]).getName());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			isFlag = service.deleteByIdString(idString);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		if (isFlag)
			message = "删除成功";
		else
			message = "删除失败";
		StringBuffer sb = new StringBuffer("[");
		sb.append("{\"message\":\"" + message + "\"" + "}");
		sb.append("]");

		try {
			out = response.getWriter();
			out.println(sb.toString());
		} catch (IOException e) {

			e.printStackTrace();
		}
		return null;
	}

	public String searchById() {
		TgBrand brand = (TgBrand) RequestUtil.getLoginUserFromSession(request,
				"brandInfo");
		TsSysuser user = (TsSysuser) RequestUtil.getLoginUserFromSession(
				request, Contants.SESSION_USER);
		String id = RequestUtil.getParam(request, "id", "");
		goods = service.getById(id);
		// List<TgCategory> pList = categoryService.findAll(1, 50);
		// TgCategory tc = categoryService.findById(Long.valueOf(goods
		// .getBrandId()));
		// List<TgCategory> cList = categoryService.findByPid(
		// new Long(tc.getPid()), -1, -1);
		// // List<TgType> typeList =
		// // typeService.findByCategoryId(Long.valueOf(goods.getTypeId()));
		// List<TgType> typeList =
		// typeService.findByCategoryId(Long.valueOf(goods
		// .getBrandId()));
		// ActionContext.getContext().put("pList", pList);
		// ActionContext.getContext().put("cList", cList);
		// ActionContext.getContext().put("typeList", typeList);
		// // ActionContext.getContext().put("btList", typeList);
		// ActionContext.getContext().put("bid", goods.getTypeId());
		// ActionContext.getContext().put("pid", tc.getPid());
		// ActionContext.getContext().put("cid", goods.getBrandId());

		List<TgCategory> pList = categoryService.findAll(1, 50);
		TgCategory tc = categoryService.findById(goods.getCategoryId());
		List<TgCategory> cList = categoryService.findByPid(
				new Long(tc.getPid()), -1, -1);
		List<TgType> typeList = typeService.findByCategoryId(goods
				.getCategoryId());
		List<TgBrand> btList = null;
		if (null == goods.getTypeId() || 0 == goods.getTypeId())
			btList = bService.findBrandByCategoryId(goods.getCategoryId());
		else
			btList = bService.findBrandByTypeId(goods.getTypeId());
		ActionContext.getContext().put("pList", pList);
		ActionContext.getContext().put("cList", cList);
		ActionContext.getContext().put("typeList", typeList);
		ActionContext.getContext().put("btList", btList);
		ActionContext.getContext().put(
				"tid",
				(null == goods.getTypeId() || 0 == goods.getTypeId() ? "0"
						: goods.getTypeId()));
		ActionContext.getContext().put("pid", tc.getPid());
		ActionContext.getContext().put("cid", goods.getCategoryId());
		ActionContext.getContext().put("bid", goods.getBrandId());
		if (null != brand && "2".equals(user.getType())) {
			return "brandmodify";
		}
		return "modify";
	}

	public TgGoods getGoods() {
		return goods;
	}

	public void setGoods(TgGoods goods) {
		this.goods = goods;
	}

	/**
	 * 得到类别、品牌下拉
	 * 
	 * @return
	 */
	public String bulidSelect() {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		// brandList = bservice.getAll();
		if (null != brandList && brandList.size() > 0) {
			message = "品牌：<select id='brandselect'>";
			for (int i = 0; i < brandList.size(); i++) {
				message += "<option value='" + brandList.get(i).getId() + "'>"
						+ brandList.get(i).getName() + "</option>";
			}
			message += "</select>";
		}
		// typeList = tervice.getList();
		if (null != typeList && typeList.size() > 0) {
			message = "类别：<select id='typeselect'>";
			for (int i = 0; i < typeList.size(); i++) {
				message += "<option value='" + typeList.get(i).getId() + "'>"
						+ typeList.get(i).getName() + "</option>";
			}
			message += "</select>";
		}
		StringBuffer sb = new StringBuffer("[");
		sb.append("{\"message\":\"" + message + "\"" + "}");
		sb.append("]");
		try {
			out = response.getWriter();
			out.println(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String loadGoodsByCategoryId() {
		try {
			String value1 = RequestUtil.getParam(request, "value1", "");
			String value2 = RequestUtil.getParam(request, "value2", "");
			rows = service.findByGoodsId(value1, value2);
			response.getWriter().print(JSONArray.fromObject(rows));
		} catch (Exception e) {
			log.error("根据种类id查找相应类别集合出错", e);
			try {
				response.getWriter().print("[]");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 修改特价商品公告
	 * 
	 * @return
	 */
	public String saveAnnouncement() {
		TgBrand brand = (TgBrand) RequestUtil.getLoginUserFromSession(request,
				"brandInfo");
		TsSysuser user = (TsSysuser) RequestUtil.getLoginUserFromSession(
				request, Contants.SESSION_USER);
		try {
			service.saveOrUpdate(goods);
		} catch (Exception e) {
		}
		if (null != brand && "2".equals(user.getType())) {
			return "brandSuccess";
		}
		return "success";
	}

	/**
	 * 查找goods商品
	 * 
	 * @return
	 */
	public String findGood() {
		String id = RequestUtil.getParam(request, "id", "");
		TgGoods goods = service.read(Long.parseLong(id));
		request.setAttribute("goods", goods);
		return "showgood";
	}

	public String findBrandGood() {
		String id = RequestUtil.getParam(request, "id", "");
		TgGoods goods = service.read(Long.parseLong(id));
		request.setAttribute("goods", goods);
		return "showBrandgood";
	}

	public String findAllGoodsByCategoryId() {
		try {
			Long categoryId = RequestUtil.getParam(request, "categoryId", 0l);
			page = RequestUtil.getParam(request, "page", 1);
			limit = RequestUtil.getParam(request, "rows", 10);
			if (page == 0)
				page = 1;
			if (limit == 0)
				limit = 10;
			PageUtil goodslist = service.findGoodsByCategoryId(categoryId,
					page, limit, true);
			total = goodslist.getTotalRecords();
			rows = goodslist.getList();
		} catch (Exception e) {
			log.error("根据行业查找商品出错", e);
		}
		return Contants.JSONSTRING_RESULT_NAME;
	}

	public String modifyWeights() {
		try {
			Long goodId = RequestUtil.getParam(request, "goodId", 0l);
			int weights = RequestUtil.getParam(request, "weights", 0);
			service.modifyGoodsWeight(goodId, weights);
			systemLogService.saveSystemLog(request, "特价抢购首页推荐", "修改权重--"+service.read(goodId).getName());
			response.getWriter().print("1");
		} catch (Exception e) {
			log.error("修改商品权重失败", e);
			try {
				response.getWriter().print("2");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 审核
	 * 
	 * @return
	 */
	public String updateMessageById() {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			String idStr = RequestUtil.getParam(request, "id", "");
			String autding = RequestUtil.getParam(request, "autding", "");
			boolean isboolean = service.updateAutingId(idStr, autding);
			out.println("{result:" + isboolean + "}");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String manageGoods(){
		catrows = catsrvice.findAll(1, 50);
		return "manageGoods";
	}
	public TgBrand getBrand() {
		return brand;
	}

	public void setBrand(TgBrand brand) {
		this.brand = brand;
	}

	public TgType getTgType() {
		return tgType;
	}

	public void setTgType(TgType tgType) {
		this.tgType = tgType;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public List getRows() {
		return rows;
	}

	public void setRows(List rows) {
		this.rows = rows;
	}

	public File getImgcomp() {
		return imgcomp;
	}

	public void setImgcomp(File imgcomp) {
		this.imgcomp = imgcomp;
	}

	public String getImgcompFileName() {
		return imgcompFileName;
	}

	public void setImgcompFileName(String imgcompFileName) {
		this.imgcompFileName = imgcompFileName;
	}

	public String getTypeId() {
		return typeId;
	}

	public void setTypeId(String typeId) {
		this.typeId = typeId;
	}

	public String getBrandId() {
		return brandId;
	}

	public void setBrandId(String brandId) {
		this.brandId = brandId;
	}

	public String getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(String categoryId) {
		this.categoryId = categoryId;
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public List<TgCategory> getCatrows() {
		return catrows;
	}

	public void setCatrows(List<TgCategory> catrows) {
		this.catrows = catrows;
	}

	public File getImgcomp1() {
		return imgcomp1;
	}

	public void setImgcomp1(File imgcomp1) {
		this.imgcomp1 = imgcomp1;
	}

	public String getImgcomp1FileName() {
		return imgcomp1FileName;
	}

	public void setImgcomp1FileName(String imgcomp1FileName) {
		this.imgcomp1FileName = imgcomp1FileName;
	}

}
